package com.itproject.redis.controller;

import com.itproject.redis.pojo.User;
import com.itproject.redis.service.RedisLockService;
import com.itproject.redis.service.RedisOptService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RequiredArgsConstructor
@RestController
public class RedisController {

    private final RedisOptService redisOptService;
    private final RedisLockService redisLockService;

    @GetMapping("/redis/set")
    public String set(@RequestParam("name") String name) {
        User user = new User();
        user.setId(RandomUtils.nextInt());
        user.setName(name);
        user.setBirthday(new Date());

        List<String> list = new ArrayList<>();
        list.add("sing");
        list.add("run");
        user.setInteresting(list);

        Map<String, Object> map = new HashMap<>();
        map.put("hasHouse", "yes");
        map.put("hasCar", "no");
        map.put("hasKid", "no");
        user.setOthers(map);

        redisOptService.set(name, user, 30000);
        User userValue = (User) redisOptService.get(name);
        return userValue.toString();
    }

    @GetMapping("/redis/lock1")
    public String lock1(@RequestParam("key") String key) throws InterruptedException {
        System.out.println("lock1 begin...");
        redisLockService.lock(key);//默認60秒後釋放鎖
        System.out.println("lock1 取得锁");
        Thread.sleep(5000L);//模拟业务逻辑处理
        System.out.println("lock1 业务处理完毕");
        redisLockService.unlock(key);
        return "Lock 1 OK";
    }

    @GetMapping("/redis/lock2")
    public String lock2(@RequestParam("key") String key) throws InterruptedException {
        System.out.println("lock2 begin...");
        redisLockService.lock(key);
        System.out.println("lock2 取得锁");
        Thread.sleep(5000L);//模拟业务逻辑处理
        System.out.println("lock2 业务处理完毕");
        redisLockService.unlock(key);
        return "Lock 2 OK";
    }

    @GetMapping("/redis/sentinel/set")
    public String sentinelSet(@RequestParam("name") String name) {
        redisOptService.set("name", name, 60000);
        return redisOptService.getStringValue("name");
    }

}
